package cn.lili.modules.permission.serviceimpl;

import cn.lili.common.enums.ResultCode;
import cn.lili.common.exception.ServiceException;
import cn.lili.common.security.AuthUser;
import cn.lili.common.security.context.UserContext;
import cn.lili.common.utils.StringUtils;
import cn.lili.modules.goods.entity.dos.Category;
import cn.lili.modules.goods.entity.vos.CategoryVO;
import cn.lili.modules.permission.entity.dos.AdminUser;
import cn.lili.modules.permission.entity.dos.Role;
import cn.lili.modules.permission.entity.dos.StoreUser;
import cn.lili.modules.permission.entity.vo.RoleVO;
import cn.lili.modules.permission.mapper.RoleMapper;
import cn.lili.modules.permission.service.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

/**
 * 角色业务层实现
 *
 * @author Chopper
 * @since 2020/11/17 3:50 下午
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

	/**
	 * 部门角色
	 */
	@Autowired
	private DepartmentRoleService departmentRoleService;
	/**
	 * 用户权限
	 */
	@Autowired
	private UserRoleService userRoleService;
	@Autowired
	private StoreUserService storeUserService;
	@Autowired
	private RoleMenuService roleMenuService;
	@Autowired
	private AdminUserService adminUserService;

	@Override
	public List<Role> findByDefaultRole(Boolean defaultRole) {
		QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("default_role", true);
		return baseMapper.selectList(queryWrapper);
	}

	@Override
	public void deleteRoles(List<String> roleIds) {
		QueryWrapper queryWrapper = new QueryWrapper<>();
		queryWrapper.in("role_id", roleIds);
		if (departmentRoleService.count(queryWrapper) > 0) {
			throw new ServiceException(ResultCode.PERMISSION_DEPARTMENT_ROLE_ERROR);
		}
		if (userRoleService.count(queryWrapper) > 0) {
			throw new ServiceException(ResultCode.PERMISSION_USER_ROLE_ERROR);
		}
		QueryWrapper queryWrappers = new QueryWrapper<>();
		queryWrappers.in("parent_id", roleIds);
		if (this.baseMapper.selectCount(queryWrappers) > 0) {
			throw new ServiceException(ResultCode.ROLE_SUBORDINATE);
		}
		// 删除角色
		this.removeByIds(roleIds);
		// 删除角色与菜单关联
		roleMenuService.remove(queryWrapper);
	}

	@Override
	public Role seleGetById(String name) {
		return baseMapper.seleGetById(name);
	}

	@Override
	public List<RoleVO> listAllChildren(String state) {
		List<Role> list = new ArrayList<>();
		if (StringUtils.isNotEmpty(state) && state.equals("1")) { // State 0 OR null平台端 1商家端
			// 商家端角色查询
			AuthUser currentUser = UserContext.getCurrentUser();
			StoreUser byId = storeUserService.getById(currentUser.getId());
			list = baseMapper.ListRole(byId.getRoleIds(), "1"); // 0平台 1商家
		} else {
			// 平台端角色查询
			AuthUser currentUser = UserContext.getCurrentUser();
			// 根据当前登录的用户去展示相应的角色
			AdminUser byId = adminUserService.getById(currentUser.getId());
			if (byId.getIsSuper()) {
				// 超级管理员角色则获取全部角色
				QueryWrapper<Role> roleQuery = new QueryWrapper<>();
				roleQuery.eq("state", "0"); // 0平台 1商家
				list = baseMapper.selectList(roleQuery);
			} else {
				// 不是超级管理员则获取当用户分配的前角色以和以下的角色
				list = baseMapper.ListRole(byId.getRoleIds(), "0"); // 0平台 1商家
			}
		}
		// 构造分类树
		List<RoleVO> categoryVOList = new ArrayList<>();
		for (Role role : list) {
			if (("0").equals(role.getParentId())) {
				RoleVO roleVO = new RoleVO(role);
				roleVO.setChildren(findChildren(list, roleVO));
				categoryVOList.add(roleVO);
			} else {
				boolean bool = true;
				for (Role r : list) {
					if (role.getParentId().equals(r.getId())) {
						// 判断集合中是否包含上级Id如果有则不进如
						bool = false;
					}
				}
				// 如果没有则构建自己的树
				if (bool) {
					RoleVO roleVO = new RoleVO(role);
					roleVO.setChildren(findChildren(list, roleVO));
					categoryVOList.add(roleVO);
				}
			}
		}
		categoryVOList.sort(Comparator.comparing(Role::getSortOrder));
		return categoryVOList;
	}

	/**
	 * 递归树形VO
	 *
	 * @param roles
	 *            角色列表
	 * @param roleVO
	 *            角色VO
	 * @return 角色VO列表
	 */
	private List<RoleVO> findChildren(List<Role> roles, RoleVO roleVO) {
		List<RoleVO> children = new ArrayList<>();
		roles.forEach(item -> {
			if (item.getParentId().equals(roleVO.getId())) {
				RoleVO temp = new RoleVO(item);
				temp.setChildren(findChildren(roles, temp));
				children.add(temp);
			}
		});
		return children;
	}

	@Override
	public Role updateRole(Role role) {
		Role role1 = this.baseMapper.selectById(role.getParentId());
		role.setAncestors(role1.getAncestors() + "," + role.getParentId());
		role.setName(role1.getName());
		this.baseMapper.updateById(role);
		return role;
	}

	@Override
	public List<String> getListRoleId(String name) {
		return this.baseMapper.getListRoleId(name);
	}
}
